package zuoye.ershouche.controller;


import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zuoye.ershouche.common.Result;
import zuoye.ershouche.entity.dto.CarInfoDTO;
import zuoye.ershouche.entity.dto.CarInfoUpdateDTO;
import zuoye.ershouche.service.CarInfoService;

import java.io.File;
import java.util.Arrays;
import java.util.UUID;

@RestController
@Api(tags = "汽车信息路由") //CarInfo
public class CarInfoController {

    @Autowired
    private CarInfoService carInfoService;


    @PostMapping(value = "/files", consumes = "multipart/form-data")
    @ApiOperation(value = "用户新增汽车类型")
    public Result addCarInfo(@ModelAttribute CarInfoDTO carInfoDTO) throws Exception {
        MultipartFile[] files = carInfoDTO.getFiles();
        if (files == null || files.length == 0) {
            return Result.error("请上传图片");
        }
        //创建基本路径
        String basePath = System.getProperty("user.dir") + "/uploads/";
        File uploadDir = new File(basePath);
        if (!uploadDir.exists()) { //如果文件目录不存在
            uploadDir.mkdirs(); // 创建目录
        }
        String[] srcs = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            String originalFilename = files[i].getOriginalFilename();
            String extension = null;
            if (originalFilename != null) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            //使用UUID保证文件名唯一
            String src = UUID.randomUUID().toString().replace("-", "") + extension;
            srcs[i] = src;
            File dest = new File(basePath + src);
            //保存文件
            files[i].transferTo(dest);
        }
        return Result.success(carInfoService.insertCarInfoWithCarImg(carInfoDTO, srcs));
    }

    @PostMapping("/delCarInfo")
    @ApiOperation(value = "用户删除出售的汽车型号")
    public Result delCarInfo(@RequestParam Integer id) {
        return Result.success(carInfoService.deleteCarInfoById(id));
    }

    @PostMapping("/updataCarInfo")
    @ApiOperation(value = "更新id修改出售的汽车型号信息")
    public Result updataCarInfo(@ModelAttribute CarInfoUpdateDTO carInfoUpdateDTO) {
        return Result.success(carInfoService.updateCarInfo(carInfoUpdateDTO));
    }

    @GetMapping("/getCarInfoById")
    @ApiOperation(value = "根据id获取汽车型号详细信息")
    public Result getCarInfoById(@RequestParam Integer id) {
        return Result.success(carInfoService.getCarInfoById(id));
    }


//    @GetMapping("/getCarInfoList")
//    @ApiOperation(value = "获取汽车型号列表(分页查询)")
//    public Result getCarInfoList(int pageSize, int pageNum) {
//        return Result.success(carInfoService.getCarInfoList(pageSize, pageNum));
//    }
}
